package com.heima.kafka.simple;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;


import java.time.Duration;
import java.util.Collections;
import java.util.Properties;

/**
 * 消费者
 */
public class ConsumerStart {

    public static void main(String[] args) {
        Properties properties = new Properties();
        // kafka 链接地址
        properties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG,"114.116.122.120:9092");
        properties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG,"org.apache.kafka.common.serialization.StringDeserializer");
        properties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG,"org.apache.kafka.common.serialization.StringDeserializer");
        properties.put(ConsumerConfig.GROUP_ID_CONFIG,"item-topic123");
        // 定义生产者
        KafkaConsumer<String, String> kafkaConsumer = new KafkaConsumer<String, String>(properties);
        // 订阅主题
        kafkaConsumer.subscribe(Collections.singletonList("kafkastream-toipc2"));

        //4.拉取消息内容
        while (true){
            ConsumerRecords<String, String> records = kafkaConsumer.poll(Duration.ofMillis(10));
            for (ConsumerRecord<String, String> record : records) {
                System.out.println("消息的key:"+record.key()+",消息的value:"+record.value());
                //表示同步提交偏移量
                //kafkaConsumer.commitSync();
                //异步提交
               /* kafkaConsumer.commitAsync(new OffsetCommitCallback() {
                    @Override
                    public void onComplete(Map<TopicPartition, OffsetAndMetadata> offsets, Exception exception) {
                        if(exception!=null){
                            System.out.println("异常信息："+exception);
                            //重试提交操作
                        }
                    }
                });*/
            }
        }
    }
}
